/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.client.user;

import net.bioteam.appweb.gwt.apps.client.StaticHolder;
import net.bioteam.appweb.gwt.apps.client.Util.ApplicationCallBack;
import net.bioteam.appweb.gwt.apps.client.Util.GwtRpcDataSource;
import net.bioteam.appweb.gwt.apps.clientandserver.user.UserAction;
import net.bioteam.appweb.model.ProgramTemplate;

import com.google.gwt.core.client.JavaScriptObject;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.fields.DataSourceDateTimeField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class TemplateDataSource extends GwtRpcDataSource
{

	private static void copyValues(ProgramTemplate from, ListGridRecord to)
	{
		to.setAttribute("id", from.getId());
		to.setAttribute("name", from.getName());
		to.setAttribute("programName", from.getProgramName());
		to.setAttribute("savedTime", from.getSavedTime());
		to.setAttribute("description", from.getDescription());
	}
	
	private static void copyValues(ListGridRecord from, ProgramTemplate to)
	{
		to.setId(Long.parseLong(from.getAttribute("id")));
		to.setName(from.getAttribute("name"));
		to.setProgramName(from.getAttribute("programName"));
		to.setSavedTime(from.getAttributeAsDate("savedTime"));
		to.setDescription(from.getAttribute("description"));
	}


	public TemplateDataSource()
	{
		super();
		DataSourceIntegerField idField = new DataSourceIntegerField("id");
		idField.setPrimaryKey(true);
		idField.setHidden(true);

		DataSourceTextField nameField = new DataSourceTextField("name");

		DataSourceTextField programNameField = new DataSourceTextField("programName");

		DataSourceDateTimeField savedTimeField = new DataSourceDateTimeField("savedTime");
		DataSourceTextField descField = new DataSourceTextField("description");

		
		setFields(idField, nameField, programNameField, savedTimeField, descField);
	}

	@Override
	protected void executeAdd(String requestId, DSRequest request, DSResponse response)
	{
		//this is not supported
		response.setStatus(RPCResponse.STATUS_FAILURE);
		processResponse(requestId, response);
	}

	@Override
	protected void executeFetch(final String requestId, final DSRequest request, final DSResponse response)
	{
		ApplicationCallBack<ProgramTemplate[]> callback = new ApplicationCallBack<ProgramTemplate[]>()
		{

			public void onFailureAfter(Throwable caught)
			{
				
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
				SC.warn(caught.getMessage(), StaticHolder.dumpB);
			}

			public void onSuccessAfter(ProgramTemplate[] result)
			{

				ListGridRecord[] list = new ListGridRecord[result.length];
				for (int i = 0; i < list.length; i++)
				{
					ListGridRecord record = new ListGridRecord();
					copyValues(result[i], record);
					list[i] = record;

				}
				
				response.setData(list);
				processResponse(requestId, response);

			}

			public void execute()
			{

				UserAction.Util.getInstance().getTemplates(this);
				}

		};
		callback.execute();

	}

	@Override
	protected void executeRemove(final String requestId, final DSRequest request, final DSResponse response)
	{
		 JavaScriptObject data = request.getData ();
	        final ListGridRecord rec = new ListGridRecord (data);
	        ApplicationCallBack<String> callback = new ApplicationCallBack<String>()
			{

				public void onFailureAfter(Throwable caught)
				{
					
					response.setStatus(RPCResponse.STATUS_FAILURE);
					processResponse(requestId, response);
					SC.warn(caught.getMessage(), StaticHolder.dumpB);
				}

				public void onSuccessAfter(String result)
				{
					ListGridRecord[] list = new ListGridRecord[1];
	                // We do not receive removed record from server.
	                // Return record from request.
	                list[0] = rec;
	                response.setData (list);
	                processResponse (requestId, response);

				}

				public void execute()
				{

					String ids[]=new String[1];
					ids[0]=rec.getAttributeAsString("id");
					UserAction.Util.getInstance().deletetemplate(ids, this);
				}

			};
			callback.execute();

	}

	@Override
	protected void executeUpdate(final String requestId, final DSRequest request, final DSResponse response)
	{
		ListGridRecord rec = getEditedRecord(request);
		final ProgramTemplate pt=new ProgramTemplate();
		copyValues(rec, pt);
		ApplicationCallBack<ProgramTemplate[]> callback = new ApplicationCallBack<ProgramTemplate[]>()
		{
			public void onFailureAfter(Throwable caught)
			{
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
				SC.warn(caught.getMessage(), StaticHolder.dumpB);
			}

			public void onSuccessAfter(ProgramTemplate[] result)
			{
				ListGridRecord[] list = new ListGridRecord[1];
				ListGridRecord updRec = new ListGridRecord();
				copyValues(result[0], updRec);
				list[0] = updRec;
				response.setData(list);
				processResponse(requestId, response);
			}

			public void execute()
			{
				ProgramTemplate[] pts = new ProgramTemplate[1];
				pts[0] = pt;
				UserAction.Util.getInstance().updateTemplates(pts, this);
			}

		};
		callback.execute();
	}

}
